package com.ajk.server.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ajk.server.controller.access.ArgIndexForPrintLog;
import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.AjkAccount;
import com.ajk.server.model.Report;
import com.ajk.server.model.ReportItem;
import com.ajk.server.model.ReportPart;
import com.ajk.server.model.ReportPartAdvice;
import com.ajk.server.model.ReportPartHealthy;
import com.ajk.server.model.request.UserReq;
import com.ajk.server.model.response.Result;
import com.ajk.server.model.response.ResultList;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.model.response.UserRes;
import com.ajk.server.security.AjkUserDetails;
import com.ajk.server.service.AjkAccountService;
import com.ajk.server.service.PartService;
import com.ajk.server.service.ReportService;
import com.ajk.server.service.UsersService;
import com.ajk.server.utils.AjkUtil;
import com.ajk.server.utils.DateUtils;
import com.ajk.server.utils.FileStoreUtil;

@Controller
@RequestMapping("/report")
public class ReportController {

	private static final Logger logger = LoggerFactory.getLogger(ReportController.class);
	
	@Autowired
	UsersService usersService;
	
	@Autowired
	private PartService partService;
	
	@Autowired
	private ReportService reportService;
	
	@Autowired
	private AjkAccountService ajkAccountService;
	
	

	/**
	 * 报告列表
	 * @param reportId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@GetMapping(value = "/list")
	public String reportList(Principal principal,Model model,Report report,HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		Integer userId = null;
		if(null != cookies) {
			for(Cookie cookie : cookies) {
				String name = cookie.getName();
				if(name.equals("accessId")) {
					String accessId = cookie.getValue();
					AjkAccount account = ajkAccountService.findByAccessId(accessId);
					if(null != account) {
						userId = account.getUserId();
					}
				}
			}
		}
		if(userId == null) {
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "未登录");
		}
		logger.info("userId : {}",userId);
		report.setUserId(userId);
		List<Report> reportList = reportService.getReportList(report);
		model.addAttribute("reportList", reportList);
		return "report/list";
	}
	
	
	/**
	 * 报告搜索页面
	 * @param reportId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@GetMapping(value = "/search/page")
	public String reportSearchPath(HttpServletRequest request){
		
		return "report/search";
	}
	
	/**
	 * 报告搜索
	 * @param reportId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@PostMapping(value = "/list/search")
	public String reportListByMobile(Principal principal,Model model,UserReq userReq,HttpServletRequest request){
		if(StringUtils.isEmpty(userReq.getMobile())  && StringUtils.isEmpty(userReq.getName())) {
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "手机号码或姓名不能为空");
		}
		Report report = new Report();
		if(StringUtils.isNotEmpty(userReq.getMobile())) {
			UserRes userRes = usersService.findUsersByMobile(userReq.getMobile());
			if(null != userRes) {
				report.setUserId(userRes.getId());
			}
		}
		if(StringUtils.isNotEmpty(userReq.getName())) {
			report.setUserName(userReq.getName());
		}
		List<Report> reportList = reportService.getReportList(report);
		model.addAttribute("reportList", reportList);
		return "report/list";
	}
	
	/**
	 * 报告详情
	 * @param reportId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@GetMapping(value = "/{reportId}")
	public String reportDetail(Principal principal,@PathVariable("reportId") Integer reportId,Model model){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Report report = reportService.getReportById(reportId);
		if(null != report) {
			Integer userId = report.getUserId() ;
			UserRes userRes = usersService.findUsersById(userId);
			model.addAttribute("user", userRes);
			String age = "未填写";
			if(userRes.getBirthday() != null) {
				age = DateUtils.getAge(userRes.getBirthday()).toString();
			}
			model.addAttribute("age", age);
			List<ReportItem> reportItemList = reportService.getReportItemByReportId(report.getId());
			for(ReportItem reportItem : reportItemList) {
				ReportPart reportPart = partService.getReportBpartById(reportItem.getPartId()); //getPartById(reportItem.getPartId());
				reportItem.setReportPart(reportPart);
				Integer level = 0;
				if(reportItem.getInfluenceLevel().equals("F")) {
					level = 6;
				}else if(reportItem.getInfluenceLevel().equals("E")) {
					level = 5;
				}else if(reportItem.getInfluenceLevel().equals("D")) {
					level = 4;
				}else if(reportItem.getInfluenceLevel().equals("C")) {
					level = 3;
				}else if(reportItem.getInfluenceLevel().equals("B")) {
					level = 2;
				}else if(reportItem.getInfluenceLevel().equals("A")) {
					level = 1;
				}
				ReportPartAdvice reportPartAdvice = partService.getPartAdviceByLevelAndPartId(reportPart.getId(), level);
				if(reportPart.getAdviceList() == null) {
					reportPart.setAdviceList(new ArrayList<>());
				}
				reportPart.getAdviceList().add(reportPartAdvice);
				if(reportItem.getInfluenceLevel().equals("C") 
					|| reportItem.getInfluenceLevel().equals("D")
					|| reportItem.getInfluenceLevel().equals("E")
					|| reportItem.getInfluenceLevel().equals("F")) {
					ReportPartHealthy reportPartHealthy = partService.getReportPartHealthy(reportItem.getPartId());
					reportPart.setReportPartHealthy(reportPartHealthy);
				}
			}
			report.setReportItemList(reportItemList);
		}
		model.addAttribute("report", report);
		return "report/detail";
	}
	
	/**
	 * 检查部位管理 - 添加
	 * @param principal
	 * @param reportPart
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@PostMapping(value = "/part/add")
	public Result addReportPart(Principal principal,@RequestBody ReportPart reportPart){
		partService.addPart(reportPart);
		return new Result();
	}
	
	/**
	 * 检查部位管理 - 修改
	 * @param principal
	 * @param reportPart
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@PostMapping(value = "/part/update")
	public Result updateReportPart(Principal principal,@RequestBody ReportPart reportPart){
		partService.updatePart(reportPart);
		return new Result();
	}
	
	/**
	 * 检查部位管理 - 修改
	 * @param principal
	 * @param reportPart
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@PostMapping(value = "/part/delete")
	public Result deleteReportPart(Principal principal,@RequestBody ReportPart reportPart){
		partService.deletePart(reportPart);
		return new Result();
	}
	
	/**
	 * 检查部位管理 - 列表
	 * @param principal
	 * @param reportPart
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@GetMapping(value = "/part/list")
	public ResultList<ReportPart> reportPartList(Principal principal,ReportPart reportPart){
		ResultList<ReportPart> list = new ResultList<>();
		List<ReportPart> reportParts = partService.getPartList(reportPart);
		list.setItemList(reportParts);
		return list;
	}
	
	/**
	 * 检查部位管理 - 列表
	 * @param principal
	 * @param reportPart
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@GetMapping(value = "/part/{id}")
	public ResultObject<ReportPart> reportPartDetail(Principal principal,@PathVariable("id") Integer id){
		ResultObject<ReportPart> resultObject = new ResultObject<>();
		ReportPart reportPart = partService.getPartById(id);
		resultObject.setDomain(reportPart);
		return resultObject;
	}
	
	
	/**
	 * 上传报告
	 * @param principal
	 * @param report
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@ResponseBody
	@PostMapping(value = "/add")
	public ResultObject<Integer> reportAdd(Principal principal,@RequestBody Report report){
		ResultObject<Integer> resultObject = new ResultObject<>();
		Integer reportId = reportService.addReport(report);
		resultObject.setDomain(reportId);
		resultObject.setExt(FileStoreUtil.getBaseUrl().concat("report/").concat(String.valueOf(reportId)));
		return resultObject;
	}
}
